from rest_framework.decorators import action
from rest_framework.viewsets import ReadOnlyModelViewSet
from meiduo_admin.my_pagination import MyPageNumberPagination
from . import order_serializers
from orders.models import OrderInfo
from rest_framework.response import Response
from rest_framework import status

# 1, order 管理
class OrderModelViewSet(ReadOnlyModelViewSet):
    pagination_class = MyPageNumberPagination
    # serializer_class = order_serializers.OrderSerializers
    # queryset = OrderInfo.objects.all()

    #1,重写get_queryset,根据keyword返回指定的数据集
    def get_queryset(self):
        #1,获取查询关键字
        keyword = self.request.query_params.get("keyword")

        #2,判断keyword
        if keyword:
            return OrderInfo.objects.filter(order_id__contains=keyword).order_by("-create_time").all()
        else:
            return OrderInfo.objects.order_by("-create_time").all()

    #2,重写get_serializer_class,判断请求方式action, 不同的action返回不同的序列化器类
    def get_serializer_class(self):
        #print("self.action = {}".format(self.action))

        #1,判断请求方式
        if self.action == "list":
            return order_serializers.OrderSerializers
        else:
            return order_serializers.OrderRetrieveSerializers

    #3, 使用action在视图集装饰一个行为, 那么就可以通过DefaultRouter,SimpleRouter自动生成路由
    @action(methods=["put"],detail=True) #生成路由的格式: orders/pk/status
    def status(self,request,*args,**kwargs):
        #1,获取参数
        status1 = request.data.get("status")
        order = self.get_object()

        #2,校验参数
        if not status:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #3,数据入库
        order.status = status1
        order.save()

        #4,返回响应
        return Response(status=status.HTTP_200_OK)